package com.iot.service;

import com.iot.core.JsonHelper;
import com.iot.mapper.*;
import com.iot.pojo.*;
import com.iot.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TdeviceServiceImpl implements TdeviceService {
    @Autowired
    private TdeviceMapper mapper;
    @Autowired
    private DTdeviceMapper dmapper;
    @Autowired
    private DRefMapper dRefMapper;
    @Autowired
    private TareaMapper dareaMapper;
    @Autowired
    private CommonService commonService;
    @Autowired
    private TappMapper dappMapper;
    @Autowired
    private Tdevice_sensorMapper tdevice_sensorMapper;
    @Autowired
    private TusersMapper tusersMapper;
    @Autowired
    private Twarn_record_detailMapper twarn_record_detailMapper;
    @Autowired
    private Twarn_recordMapper twarn_recordMapper;
    @Autowired
    private Twarn_typeMapper twarn_typeMapper;
    @Autowired
    private TempMapper tempMapper;

    @Override
    public int getRecordCount(String sWhere) {

        return mapper.getRecordCount(sWhere);
    }

    @Override
    public int insert(MTdevice mTdevice) throws Exception {
        int count = 0;
        if (!mTdevice.getIMEI().trim().isEmpty()) {
            count = getRecordCount(" AND IMEI='" + mTdevice.getIMEI() + "'");
            if (count > 0)
                throw new Exception("该设备信息已存在!");
        }
        mTdevice.setCODE(Common.getUUID());
        return mapper.insert(mTdevice);
    }

    @Override
    public void update(MTdevice mTdevice) throws Exception {
        int count = 0;
        if (!mTdevice.getIMEI().trim().isEmpty()) {
            count = getRecordCount(" AND IMEI='" + mTdevice.getIMEI() + "' AND DEVICE_ID!=" + mTdevice.getDEVICE_ID() + "");
            if (count > 0)
                throw new Exception("该设备信息已存在!");
        }
        mapper.update(mTdevice);
    }

    @Override
    public void deleteById(int id) {
        mapper.deleteById(id);
    }

    @Override
    public MTdevice single(Integer id) {
        return mapper.single(id);
    }

    @Override
    public List<MTdevice> fetch(String sWhere) {
        return mapper.fetch(sWhere);
    }

    @Override
    public List<Map<String, Object>> fetchByPage(Map<String, Object> map) throws Exception {
        try {
            return dmapper.fetchByPage(map);
        } catch (Exception ex) {
            throw new Exception(ex.getMessage());
        }
    }


    @Override
    public List<Map<String, Object>> getDeviceById(Map<String, Object> map) {
        List<Map<String, Object>> tempMap = dmapper.getDeviceById(map);
        return getDoorStatus(tempMap);
    }


    @Override
    public Map<String, Object> initList() {
        Map<String, Object> map = new HashMap<>();
        List<MRef> provinceList = dRefMapper.getProvince();
        map.put("province", provinceList);
        List<MRef> typeList = dRefMapper.getDeviceType();
        map.put("type", typeList);
        List<MRef> protocolList = dRefMapper.getDeviceProtocol();
        map.put("protocol", protocolList);
        return map;
    }

//    @Override
//    public Map<String, Object> initCityById(Map<String, Object> map) {
//        Map<String, Object> resmap = new HashMap<>();
//        List<MRef> cityList = dRefMapper.getCity(map);
//        resmap.put("city", cityList);
//        return resmap;
//    }
//
//    @Override
//    public Map<String, Object> initAreaById(Map<String, Object> map) {
//        Map<String, Object> resmap = new HashMap<>();
//        List<MRef> areaList = dRefMapper.getArea(map);
//        resmap.put("area", areaList);
//        return resmap;
//    }

//    @Override
//    public Map<String, Object> initRegionById(Map<String, Object> map) {
//        Map<String, Object> resmap = new HashMap<>();
//        List<MRef> regionList = dRefMapper.getRegion(map);
//        resmap.put("region", regionList);
//        return resmap;
//    }

//    @Override
//    public Map<String, Object> initSiteById(Map<String, Object> map) {
//        Map<String, Object> resmap = new HashMap<>();
//        List<MRef> list = dRefMapper.getSite(map);
//        resmap.put("site", list);
//        return resmap;
//    }

//    @Override
//    public Map<String, Object> initLineById(Map<String, Object> map) {
//        Map<String, Object> resmap = new HashMap<>();
//        List<MRef> lineList = dRefMapper.getLine(map);
//        resmap.put("line", lineList);
//        return resmap;
//    }

    @Override
    public Map<String, Object> initDeviceScaleById(Map<String, Object> map) {
        Map<String, Object> resmap = new HashMap<>();
        List<MRef> scaleList = dRefMapper.getDeviceScale(map);
        resmap.put("scale", scaleList);
        return resmap;
    }


    @Override
    public Map<String, Object> initEdit(int appId) {
        MTapp mTapp = commonService.getApp(appId);
        Map<String, Object> map = new HashMap<>();
        List<MRef> areaList = dRefMapper.getArea(mTapp.getCITY_ID());
        map.put("area", areaList);
        List<MRef> typeList = dRefMapper.getDeviceType();
        map.put("type", typeList);
        List<MRef> protocolList = dRefMapper.getDeviceProtocol();
        map.put("protocol", protocolList);
        return map;
    }

    @Override
    public List<Map<String, Object>> getAllDevice(Map<String, Object> map) {

        MTusers muser = tusersMapper.singleByWhere(" AND USERS_ID=" + map.get("userId"));

        if (muser != null) {
            map.put("badmin", muser.getBADMIN());
        } else {
            map.put("badmin", 1);
        }


        List<Map<String, Object>> deviceMap = dmapper.getAllDevice(map);


        return getDoorStatus(deviceMap);
    }

    private List<Map<String, Object>> getDoorStatus(List<Map<String, Object>> deviceMap) {
        for (Map<String, Object> tempMap :
                deviceMap) {
            tempMap.put("DOORDESC", "");
            tempMap.put("DOORSTATUS", "");
            tempMap.put("BATTERYLEVEL", "");
            tempMap.put("EMP_IDNAME", "");
            tempMap.put("WARNSTATUS", "");
            tempMap.put("WARNSDESC", "");
            tempMap.put("LOCKSTATUS", "");
            tempMap.put("LOCKDESC", "");
            tempMap.put("SENSORDATE", "");
            tempMap.put("SOAKING", "");
            tempMap.put("TEMPERATURE", "");
            tempMap.put("HUMIDITY", "");
            tempMap.put("QUAKE", "");
            tempMap.put("TILT", "");
            int deviceId = Common.toInt(tempMap.get("DEVICE_ID"));
            MTdevice md = mapper.single(deviceId);
            MTwarn_record mTwarn_record = twarn_recordMapper.singleByWhere("AND DEVICE_ID=" + deviceId + "  ORDER BY SDATE DESC ");
            if (mTwarn_record != null) {
                MTwarn_type mTwarnType = twarn_typeMapper.single(mTwarn_record.getWARN_TYPE_ID());
                if (mTwarnType != null) {
                    if (mTwarnType.getMEANCODE() > 1) {
                        tempMap.put("WARNSTATUS", 1);
                        tempMap.put("WARNSDESC", mTwarnType.getSNAME());
                    } else {
                        tempMap.put("WARNSTATUS", 0);
                    }

                }
                tempMap.put("SENSORDATE", mTwarn_record.getSDATE());
                if (md.getTYPE_ID() == 1) {
                    MTnb_dev_data data = JsonHelper.toBean(mTwarn_record.getJSONSTR(), MTnb_dev_data.class);
                    MTemp mTemp = tempMapper.single(mTwarn_record.getEMP_ID());
                    String doors = YT.decimalToBinary(data.getDOORLOCK());
                    int mdoors = md.getDOOR_NUM();
                    String descDoor = " ";
                    for (int i = 0; i < mdoors; i++) {
                        char ch = doors.charAt(i);
                        if (ch == '1') {
                            descDoor += (i + 1) + "号门被打开 ";
                        } else {
                            descDoor += (i + 1) + "号门关闭 ";
                        }
                    }

                    if (Common.toInt(data.getDOORLOCK()) > 0) {
                        tempMap.put("DOORSTATUS", 1);
                    } else {
                        tempMap.put("DOORSTATUS", 0);
                    }

                    tempMap.put("DOORDESC", descDoor.trim());
                    //电量
                    tempMap.put("BATTERYLEVEL", data.getBATTERYLEVEL());
                    //进水
                    tempMap.put("SOAKING", data.getSOAKING());
                    //温度
                    tempMap.put("TEMPERATURE", data.getTEMPERATURE());
                    //湿度
                    tempMap.put("HUMIDITY", data.getHUMIDITY());
                    //震动
                    tempMap.put("QUAKE", data.getQUAKE());
                    //倾斜
                    tempMap.put("TILT", data.getTILT());
                    //电磁锁
                    if (Common.toInt(data.getLOCKSTATUS()) > 0) {
                        tempMap.put("LOCKSTATUS", 1);
                    } else {
                        tempMap.put("LOCKSTATUS", 0);
                    }
                    String descLock = " ";
                    String lock = YT.decimalToBinary(data.getLOCKSTATUS());
                    for (int i = 0; i < mdoors; i++) {
                        char ch = lock.charAt(i);
                        if (ch == '1') {
                            descLock += (i + 1) + "号锁被打开 ";
                        } else {
                            descLock += (i + 1) + "号锁关闭 ";
                        }
                    }
                    tempMap.put("LOCKDESC", descLock);

                    if (mTemp != null) {
                        tempMap.put("EMP_IDNAME", mTemp.getSNAME());
                    }
                }
            }
        }
        return deviceMap;
    }

    @Override
    public MTapp getTapp(int appId) {
        return dappMapper.single(appId);
    }

    @Override
    public Map<String, Object> getAllDevice1(Map<String, Object> map) {
        List<Map<String, Object>> list = dmapper.getAllDevice(map);
        List<GeoCoordinate> geoCoordinateList = new ArrayList<GeoCoordinate>();
        CenterPointAndZoom cp = new CenterPointAndZoom();

        if (list.size() > 0) {
            for (Map<String, Object> item :
                    list) {
                GeoCoordinate g = new GeoCoordinate(Common.toDouble(item.get("LATITUDE")), Common.toDouble(item.get("LONGITUDE")));
                geoCoordinateList.add(g);
            }
            cp = CenterPoint.GetCenterPointAndZoom(geoCoordinateList);
        }

        list = getDoorStatus(list);
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("list", list);
        resMap.put("cpz", cp);
        return resMap;
    }

    @Override
    public int Save(Map<String, Object> map) throws Exception {
        MTdevice entity = new MTdevice();

        entity.setTYPE_ID(Common.toInt(map.get("typeId")));
        entity.setSNAME(map.get("sname").toString());
        entity.setBDEL(1);
        entity.setPROTOCOL_ID(Common.toInt(map.get("protocolId")));
        entity.setSCALE_ID(Common.toInt(map.get("scaleId")));
        entity.setAPP_ID(Common.toInt(map.get("appId")));

        entity.setLATITUDE(map.get("lat").toString());
        entity.setLONGITUDE(map.get("lon").toString());
        entity.setCODE(Common.getWorkNo());
        entity.setSTATUS_ID(6);
        String code = map.get("adcode").toString();
        String imei = map.get("imei").toString();
        entity.setIMEI(imei);

        String doorNum = map.get("door_num").toString();
        entity.setDOOR_NUM(Common.toInt(doorNum));

        MTarea mtemp = dareaMapper.singleByWhere("AND CODE='" + code + "'");
        if (mtemp != null) {
            entity.setAREA_ID(mtemp.getAREA_ID());
        }
        mtemp = dareaMapper.single(mtemp.getPID());
        if (mtemp != null) {
            entity.setCITY_ID(mtemp.getAREA_ID());
        }
        mtemp = dareaMapper.single(mtemp.getPID());
        if (mtemp != null) {
            entity.setPROVINCE_ID(mtemp.getAREA_ID());
        }
        int count = 0;
        if (entity.getIMEI().trim() != "") {
            count = getRecordCount(" AND IMEI='" + entity.getIMEI() + "'");
            if (count > 0)
                throw new Exception("该设备信息已存在!");
        }
        mapper.insert(entity);
        return entity.getDEVICE_ID();
    }

    @Override
    public List<Map<String, Object>> getDeviceImages(Map<String, Object> map) {

        return dmapper.getDeviceImages(map);
    }

    @Override
    public List<Map<String, Object>> getDeviceSensor(int deviceId) {

        MTdevice model = mapper.single(deviceId);

        List<MTdevice_sensor> list = tdevice_sensorMapper.fetch(" AND TYPE_ID=" + model.getTYPE_ID() + "");
        List<Map<String, Object>> detail = new ArrayList<>();
        for (MTdevice_sensor item :
                list) {
            //twarn_record_detailMapper.singleByWhere(" AND DEVICE_ID="+deviceId+" AND SENSOR_ID="+item.getSENSOR_ID()+" ORDER BY WARN_RECORD_ID DESC");
            List<Map<String, Object>> map = dmapper.getDeviceSensorData(deviceId, item.getSENSOR_ID());
            //    detail.addAll(0, map);
            Map<String, Object> map1 = new HashMap<>();
            map1.put("SENSOR_ID", item.getSENSOR_ID());
            map1.put("SNAME", item.getSNAME());
            if (map.size() > 0) {
                if (item.getSENSOR_ID() == 1 || item.getSENSOR_ID() == 7 || item.getSENSOR_ID() == 9) {
                    if (Common.toInt(map.get(0).get("VAL")) > 0) {
                        String doors = YT.decimalToBinary(Common.toInt(map.get(0).get("VAL")));
                        int mdoors = model.getDOOR_NUM();
                        String descO = "";
                        String descC = "";
                        String staO = "";
                        String staC = "";
                        for (int i = 0; i < mdoors; i++) {
                            char ch = doors.charAt(i);
                            if (ch == '1') {
                                descO += (i + 1) + "、";
                                staO = "开";
                            } else {
                                descC += (i + 1) + "、";
                                staC = "关";
                            }

                        }

                        String val = "";
                        if (descO.length() > 0) {
                            descO = descO.substring(0, descO.length() - 1);
                            val += descO + "号" + staO + "-";
                        }
                        if (descC.length() > 0) {
                            descC = descC.substring(0, descC.length() - 1);
                            val += descC + "号" + staC + "-";
                        }

                        map1.put("VAL", val.substring(0, val.length() - 1));
                    } else {
                        map1.put("VAL", "关");
                    }
                } else {
                    map1.put("VAL", map.get(0).get("VAL"));
                }
            } else {
                map1.put("VAL", "");
            }
            detail.add(map1);
        }
        //  Map<String, Object> resMap = new HashMap<>();
        // resMap.put("sensor", list);
        // resMap.put("sensorData", detail);
        return detail;
    }

}
